package com.abing.permissionsys.timing.utils;

import com.abing.core.utils.BeanUtil;
import com.abing.core.utils.CronUtil;
import com.abing.core.utils.SpringContextHolder;
import com.abing.permissionsys.entity.vo.TimingJobLogVO;
import com.abing.permissionsys.entity.vo.TimingJobVO;
import com.abing.permissionsys.service.TimingJobLogService;
import com.abing.permissionsys.service.TimingJobService;
import com.abing.permissionsys.timing.thread.ThreadPoolExecutorUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.springframework.scheduling.quartz.QuartzJobBean;

import java.util.Date;
import java.util.concurrent.Future;
import java.util.concurrent.ThreadPoolExecutor;


/**
 * 定时任务
 *
 * @author Mark sunlightcs@gmail.com
 */
@Slf4j
public class ScheduleJob extends QuartzJobBean {

	// 该处仅供参考
	private final static ThreadPoolExecutor executor = ThreadPoolExecutorUtil.getPoll();


    @Override
    protected void executeInternal(JobExecutionContext context) throws JobExecutionException {
		TimingJobVO timingJob = (TimingJobVO) context.getMergedJobDataMap().get(TimingJobVO.JOB_PARAM_KEY);
        //获取spring bean
		TimingJobLogService timingJobLogService = SpringContextHolder.getBean(TimingJobLogService.class);
		TimingJobService timingJobService = SpringContextHolder.getBean(TimingJobService.class);

        //数据库保存执行记录
		TimingJobLogVO timingLog = BeanUtil.change(timingJob, TimingJobLogVO.class);
		timingLog.setId(null);
        
        //任务开始时间
        long startTime = System.currentTimeMillis();
        
        try {
            //执行任务
        	log.debug("任务准备执行，任务："+timingJob.getClassName());

			QuartzRunnable task = new QuartzRunnable(timingJob.getClassName());
			Future<?> future = executor.submit(task);
			future.get();


//			Object target = SpringContextHolder.getBean(timingJob.getClassName());
//			Method method = target.getClass().getDeclaredMethod("run");
//			method.invoke(target);
			//任务执行总时长
			long times = System.currentTimeMillis() - startTime;
			timingLog.setTimes(String.valueOf(times));
			//任务状态    0：成功    1：失败
			timingLog.setState("0");
			
			log.debug("任务执行完毕，任务：" + timingJob.getClassName() + "  总共耗时：" + times + "毫秒");
		} catch (Exception e) {
			log.error("任务执行失败，任务：" + timingJob.getClassName(), e);
			
			//任务执行总时长
			long times = System.currentTimeMillis() - startTime;
			timingLog.setTimes(String.valueOf(times));
			
			//任务状态    0：成功    1：失败
			timingLog.setState("1");
			timingLog.setErrors(e.toString());
		}finally {
        	//保存日志
			timingLog.setCreateTime(new Date());
			timingJobLogService.save(timingLog);
			//更薪job表下次执行时间
			TimingJobVO timingJobVO=new TimingJobVO();
			timingJobVO.setId(timingJob.getId());
			timingJobVO.setNextExecuteTime(CronUtil.getNextTriggerTime(timingJob.getCronExpression()));
			timingJobVO.setPrevExecuteTime(CronUtil.getPrevTriggerTime(timingJob.getCronExpression()));
			timingJobService.updateTime(timingJobVO);
		}
    }
}
